# -- coding: utf-8 --
# @Time : 2024/2/5 08:36
# @Author : rlh
# @File : Api_data_models.py
# 功能描述:
import random
import datetime
import re



# 系统第三方库
from exts import db
# 导入项目模块
class ApiData(db.Model):
    __tablename__ = 'api_data'
    _id = db.Column(db.String(17), name='id',primary_key=True,unique=True)
    _api_name = db.Column(db.String(64), name='api_name', nullable=True, unique=True)
    _url_path = db.Column(db.String(255), name='url_path', unique=True)
    template = db.Column(db.String(255))
    description = db.Column(db.Text,)

    def __init__(self, api_name, url_path, template, description):
        self._id = self.generate_id()
        self.api_name = api_name
        self.url_path = url_path
        self.template = template
        self.description = description


    @staticmethod
    def generate_id():
        current_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        random_digits = random.randint(100,999)
        return "{}{}".format(current_time, random_digits)

    @property
    def api_name(self):
        return self._api_name

    @api_name.setter
    def api_name(self, text):
        if text:
            # 正则表达式模式，只匹配英文字符
            pattern = "^[A-Za-z0-9]+"
            # 使用re.match函数检查文本是否与模式匹配
            if re.match(pattern, text):
                self._api_name = text
            else:
                # logs.log('error', '初始化api_name')('api_name必须为英文字符')
                raise ValueError('api_name必须为英文字符')
        else:
            raise ValueError('api_name不能为空')



    @property
    def url_path(self):
        return self._url_path

    @url_path.setter
    def url_path(self, text):
        if text:
            if not text.startswith('/'):
                text = '/'+text
            self._url_path = text
        else:
            raise ValueError('url不能为空')



